package startup

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"jk-time/webook/internal/web"
	ijwt "jk-time/webook/internal/web/jwt"
	"jk-time/webook/internal/web/middleware"
	"strings"
	"time"
)

// InitMiddlewares -> mdls
func InitGin(mdls []gin.HandlerFunc, userHdl *web.UserHandler,
	wechat *web.OAuth2WechatHandler, github *web.OAuth2GithubHandler, artHdl *web.ArticleHandler) *gin.Engine {
	server := gin.Default()
	server.Use(mdls...)
	userHdl.RegisterRouters(server)
	wechat.RegisterRoutes(server)
	github.RegisterRoutes(server)
	artHdl.RegisterRouters(server)
	return server
}
func InitMiddlewares(handler ijwt.Handler) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		corsHdl(),
		middleware.NewLoginJWTMiddlewareBuilder(handler).
			IgnorePaths("/users/login").
			IgnorePaths("/users/signup").
			IgnorePaths("/users/login_sms/code/send").
			IgnorePaths("/users/login_sms").
			IgnorePaths("/users/login_sms").
			IgnorePaths("/users/refresh_token").
			IgnorePaths("/oauth2/wechat/authurl").
			IgnorePaths("/oauth2/wechat/callback").
			CheckLogin(),
		//ratelimit.NewBuilder(cmd, time.Minute, 100).Build(),
	}
}
func corsHdl() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowHeaders: []string{"Content-Type", "Authorization"},
		//是否允许携带用户验证信息
		AllowCredentials: true,
		//不加这个，前端拿不到
		ExposeHeaders: []string{"X-Jwt-Token"},
		//是否允许来源
		AllowOriginFunc: func(origin string) bool {
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "")
		},
		MaxAge: 12 * time.Hour,
	})
}
